package com.zhu.rpc;

import com.sun.scenario.effect.impl.sw.sse.SSEBlend_SRC_OUTPeer;
import com.zhu.rpc.client.RpcClient;
import com.zhu.rpc.client.RpcRequest;
import com.zhu.rpc.server.RpcServer;
import io.netty.channel.ChannelFuture;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.CommandLineRunner;
import org.springframework.stereotype.Component;

@Component
public class RpcServerRun implements CommandLineRunner {


    @Autowired
    private RpcConf rpcConf;

    @Value("${orpc.port}")
    private Integer port;
    @Value("${orpc.host}")
    private String host;

    private Logger logger = LoggerFactory.getLogger(RpcServerRun.class);
    /**
     * Callback used to run the bean.
     *
     * @param args incoming main method arguments
     * @throws Exception on error
     */
    @Override
    public void run(String... args) throws Exception {
        RpcServer rpcServer = new RpcServer();
        rpcServer.start(port,host);
        clientConnect();
    }

    void clientConnect(){
        RpcClient rpcClient = new RpcClient();

        if (rpcConf.getHost() == null){
            logger.error("没有客户端");
        }else {
            rpcConf.getHost().keySet().forEach(key->{
                String host = rpcConf.getHost().get(key);
                int port = rpcConf.getPort().get(key);
                //重试60次 每次隔5s
                for (int i = 0; i < 60; i++) {
                    try {
                        ChannelFuture channelFuture = rpcClient.connect(port,host,key);
                        RpcRequest.setNettyChannel(key,channelFuture.channel());
                        logger.info("成功");
                        break;
                    }catch (Exception e) {
                        logger.error("服务{}连接失败，重试",key);
                        try {
                            Thread.sleep(5000);
                        } catch (InterruptedException e1) {
                            e1.printStackTrace();
                        }
                    }
                }

            });
        }

    }
}
